'use strict';

/**
 * Module dependencies.
 */
var Schema = require('mongoose').Schema,
    Model = require('../../../Base/server/controllers/Model'),
    crypto = require('crypto'),
    validator = require('validator');

/**
 * A Validation function for local strategy email
 */
// var validateLocalStrategyEmail = function(email) {
//     return (!this.updated || validator.isEmail(email));
// };

var validateLocalStrategyPassword = function(password) {
    return (password && password.length >= 6);
};


var modelField = {};
modelField.Code = {
    type: String,
    Name: '编码',
    IsUnique: true,
    IsEmpty: false,
    trim: true
};
modelField.Name = {
    type: String,
    trim: true,
    Name: '名称',
    IsEmpty: false
};
modelField.Password = {
    type: String,
    default: '123456',
    validate: [validateLocalStrategyPassword, '密码至少6位']
};
modelField.Image = {
    type: String,
    default: 'users/img/default.png'
};
modelField.Email = {
    type: String,
    trim: true,
    default: ''
        //validate: [validateLocalStrategyEmail, '请输入一个合法的邮箱']
};
modelField.Salt = {
    type: String
};
modelField.Roles = {
    type: [{
        type: Schema.ObjectId,
        ref: 'Role'
    }]
};
modelField.AppRoles = {
    type: [{
        type: Schema.ObjectId,
        ref: 'AppRole'
    }]
};
modelField.Phone = {
    type: String,
    trim: true
};
//唯一标识
modelField.UniqueID = {
    type: String,
    trim: true
};
modelField.IsEffective = {
    type: Boolean
};
modelField.Remark = {
    type: String
};

/* For reset password */
modelField.ResetPasswordToken = {
    type: String
};
modelField.ResetPasswordExpires = {
    type: Date
};

//2016-10-26 增加用户对 U9的企业和用户的映射 用于生单调用U9服务 --lwd
modelField.ErpEntCode ={
    type : String,
    trim : true
};

modelField.ErpUserCode ={
    type : String,
    trim : true
};

modelField.Orgs = {
    type: [{
        type: Schema.ObjectId,
        ref: 'Org'
    }]
};

var newModel = new Model(modelField);
newModel.addIndex({ Name: 1 });
newModel.addIndex({ Code: 1 }, { "unique": true });

/**
 * Hook a pre save method to hash the password
 */
newModel.Schema.pre('save', function(next) {
    if (this.Password && this.isModified('Password') || this.Password === '123456') {
        this.Salt = crypto.randomBytes(16).toString('base64');
        this.Password = this.hashPassword(this.Password);
    }
    if (this.Name === '') {
        this.Name = this.Code;
    }

    next();
});

/**
 * Create instance method for hashing a password
 */
newModel.Schema.methods.hashPassword = function(password) {
    if (this.Salt && password) {
        return crypto.pbkdf2Sync(password, new Buffer(this.Salt, 'base64'), 10000, 64).toString('base64');
    } else {
        return password;
    }
};

/**
 * Create instance method for authenticating user
 */
newModel.Schema.methods.authenticate = function(password, callback) {
    callback(this.Password === this.hashPassword(password));
};

/**
 * Find possible not used username
 */
newModel.Schema.statics.findUniqueUsername = function(username, suffix, callback) {
    var _this = this;
    var possibleUsername = username.toLowerCase() + (suffix || '');

    _this.findOne({
        Name: possibleUsername
    }, function(err, user) {
        if (!err) {
            if (!user) {
                callback(possibleUsername);
            } else {
                return _this.findUniqueUsername(username, (suffix || 0) + 1, callback);
            }
        } else {
            callback(null);
        }
    });
};

newModel.create('User', '用户');
